package com.ws.server.formal;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class WebSocketServer {
	private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);
	/** 用于分配处理业务线程的线程组个数 */
	protected static final int BIZGROUPSIZE = 1;
	// netty_worker_size
	private static Integer BIZTHREADSIZE = Integer.valueOf(8);
	private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
	private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
	private Integer port = 8080;

	public void run() throws Exception {
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)
			.childHandler(new ServerInitializer())
			.option(ChannelOption.SO_BACKLOG, 128)
			.childOption(ChannelOption.TCP_NODELAY, true)
			.childOption(ChannelOption.SO_KEEPALIVE, true);
			Channel ch = b.bind(new InetSocketAddress(port)).sync().channel();
			LOGGER.warn("server started at port {}", port);
			ch.closeFuture().sync();
		} catch (Exception e) {
			LOGGER.error("{}", e);
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	public void close() {
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}
}
